package com.example.school.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userName = (String) request.getSession().getAttribute("userName");

        if (userName != null) {
            log.info("已通过验证");
            response.setStatus(200);
            if (request.getRequestURI().startsWith("/student/")) {
                String userRole = (String) request.getSession().getAttribute("role");
                if (userRole != null && userRole.equals("student")) {
                    return true;
                } else {
                    log.info("请求被拦截，用户不是学生");
                    response.setStatus(403); // Forbidden
                    return false;
                }
            } else if (request.getRequestURI().startsWith("/teacher/")) {
                String userRole = (String) request.getSession().getAttribute("role");
                if (userRole != null && userRole.equals("teacher")) {
                    return true;
                } else {
                    log.info("请求被拦截，用户不是老师");
                    response.setStatus(403); // Forbidden
                    return false;
                }
            } else {
                return true;
            }
        } else {
            log.info("请求已进入拦截器");
            response.setStatus(401); // Unauthorized
            return false;
        }
    }
}
